package com.woniuxy.util;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

/**
 * @author gaopeng
 * @create 2020/04/2020/4/8 16:31:53
 */
public class MyRobinRule extends AbstractLoadBalancerRule {

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
    }

    private int index = 0;
    private int currTime = 0;
    private int maxTimes = 3;

    public Server choose(ILoadBalancer lb, Object key) {
        List<Server> allServers = lb.getAllServers();
        int size = allServers.size();

        Server server = allServers.get(index);
        currTime++;
        if(currTime >= maxTimes) {
            index++;
            currTime = 0;
            if(index >= size) {
                index = 0;
            }
        }
        return server;
    }

    @Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }
}
